<template>
  <!--分案日期策略 新增/修改-->
  <section class="component modify-role">
    <el-form :model="divisionModel" :rules="rules" ref="form" label-width="90px" class="tableInput">
      <el-row>
        <el-col :span="12">
          <el-form-item label="策略代码" prop="strategyNo">
            <el-input v-model.trim="divisionModel.strategyNo" :disabled="show" :maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="策略名称" prop="strategyName">
            <el-input v-model.trim="divisionModel.strategyName" :disabled="show" :maxlength="20"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="widthFour">
          <el-form-item label="策略状态" prop="state">
            <el-select v-model="divisionModel.state" placeholder="请选择" :disabled="show">
              <el-option v-for="{ index, name, code } in $dict.getDictData('CommonState')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="widthFour">
          <el-form-item label="分案状态" prop="divisionState">
            <el-select @change="divisionStateChange" v-model="divisionModel.divisionState" placeholder="请选择" :disabled="show">
              <!-- <el-option v-for="{ index, name, code } in $dict.getDictData('CommonState')" :key="index" :label="name" :value="code"></el-option> -->
              <el-option label="执行分案" value="do">执行分案</el-option>
              <el-option label="暂不分案" value="undo">暂不分案</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :style="{marginBottom:marginBottom+'px'}">
        <el-col class="widthOne">
          <el-form-item label="策略日期" prop="operationDate" id="division" v-if="!show">
            <el-select v-model="divisionModel.operationDate" @focus="X" multiple placeholder="请选择" :disabled="show || disableDate">
              <el-option id="option" v-for="item in 31" :key="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="策略日期" prop="editOperationDate" id="division" v-else>
            <el-select v-model="divisionModel.editOperationDate" @focus="X" multiple placeholder="请选择" :disabled="show">
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="策略注记" prop="remark">
            <el-col class="widthTwo">
              <el-input type="textarea" v-model.trim="divisionModel.remark" :rows="3" :maxlength="500" :disabled="show" show-word-limit></el-input>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showApproval" style="margin-left:10px">{{`申请人代号&nbsp;&nbsp;&nbsp;${divisionModel.operatorCode===null?'超级管理员':divisionModel.operatorCode}`}}</el-row>
      <el-row v-if="showApproval">
        <el-col class="widthThree">
          <el-form-item label="审批历史">
            <data-box :data="dataset" @onPageChange="refreshData" class="paddingNone">
              <template slot="columns">
                <el-table-column prop="approvalRealName" label="审批人" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalTime" label="审批时间" :formatter="row => $filter.dateTimeFormat(row.approvalTime)" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="applyStatus" label="审批结果" :formatter="row => $filter.dictConvert(row.applyStatus,'ApplyStatus')" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalOpinion" label="审批意见" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showHidden">
        <el-col class="widthThree">
          <el-form-item label="策略历史注记">
            <data-box :data="dataHistory" @onPageChange="refreshData" class="paddingNone">
              <template slot="columns">
                <el-table-column prop="createTime" label="注记时间" :formatter="row => $filter.dateTimeFormat(row.createTime)" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="operatorRealName" label="添加人" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="remark" label="内容" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="!show" class="operate-buttons">
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">{{`${operationType.DEFAULT==='OPERATION_ADD'?'保存':'提交审批'}`}}</el-button>
    </div>
    <div v-else class="operate-buttons">
      <el-button @click="close">关闭</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { DateStrategyService } from "~/services/management-service/date-strategy.service";
import { CaseApplyRecordService } from "~/services/domain-service/case-apply-record.service"
import { Emit, Prop, Watch } from "vue-property-decorator";
import { OPERATION_TYPE } from "~/config/enum.config";

@Component({
  components: {}
})
export default class AddDivision extends Vue {
  @Dependencies(DateStrategyService)
  private dateStrategyService: DateStrategyService;
  @Dependencies(CaseApplyRecordService)
  private caseApplyRecordService: CaseApplyRecordService;
  @Prop({ type: Object })
  private roleData: any;
  @Prop({ type: String })
  private type: string
  private dataset: any[] = []
  private dataHistory: any[] = []
  private show: boolean = false
  private disableDate = false
  private showHidden: boolean = false
  private showApproval: boolean = false
  private divisionModel: any = {
    id: "",
    strategyNo: '',
    strategyName: '',
    operationDate: [],
    editOperationDate: [], // 查看时日期组件数据
    remark: '',
    state: '',
    divisionModel: '',
    divisionState: ''
  };
  private marginBottom: number = 0
  // 页面按钮类型
  private operationType: any = OPERATION_TYPE
  private rules: any = {
    strategyNo: [{ required: true, message: "请输入策略代码", trigger: "blur" },
    { message: "输入字符不合法", trigger: "blur", validator: this.$validator.numberStr }],
    strategyName: [{ required: true, message: "请输入策略名称", trigger: "blur" }],
    operationDate: [{ required: true, message: "请选择策略日期", trigger: "change" }],
    remark: [{ required: true, message: "策略注记不能超过500字符", trigger: "blur" }],
    state: [{ required: true, message: "请选择策略状态", trigger: "change" }]
  };

  @Emit("refreshData")
  public refreshData () { }
  @Emit("refreshList")
  public refreshList () { }
  @Emit("close")
  public close () {
    this.refreshData();
  }
  /**
   * 新增/修改  策略日期下拉框动态高度样式
   */
  @Watch('divisionModel.operationDate') private change () {
    this.marginBottom = 0
    this.divisionModel.operationDate && this.divisionModel.operationDate.length > 9 ? this.marginBottom += 20 : this.marginBottom = 0
  }
  /**
   * 分案策略日期组件样式
   */
  private X () {
    const dom: any = document.getElementById('option')
    dom.parentNode.style = 'max-width:500px;padding:10px;display:flex;align-items:center;justify-content:left;flex-wrap: wrap'
  }
  private reset () {
    const from: any = this.$refs["form"];
    from.resetFields();
    // 队列显示
    this.showHidden = (this.operationType.DEFAULT === 'OPERATION_ADD' || this.operationType.DEFAULT === 'APPROVAL_LOG') ? false : true;
    // 禁用
    this.show = (this.operationType.DEFAULT === 'APPROVAL_LOG' || this.operationType.DEFAULT === 'OPERATION_SEE') ? true : false;
    //审批显示
    this.showApproval = (this.operationType.DEFAULT === 'APPROVAL_LOG') ? true : false
    this.disableDate = false
    if (this.operationType.DEFAULT !== 'OPERATION_ADD') {
      this.divisionModel = { ...this.roleData }
      this.divisionModel.divisionState = 'do'
    } else {
      this.divisionModel = {
        id: "",
        strategyNo: '',
        strategyName: '',
        operationDate: [],
        editOperationDate: [], // 查看时日期组件数据
        remark: '',
        state: '',
        divisionModel: '',
        divisionState: 'do'
      };
    }
    //编辑时
    if (this.operationType.DEFAULT === 'OPERATION_EDIT' || this.operationType.DEFAULT === 'OPERATION_SEE') this.beforeUpdating();

    // 查询一条策略日志
    if (Object.keys(this.roleData).length !== 0) { this.findSrategy() }

    // 审批记录
    if (this.show) { this.apply() }
  }

  /**
   * 查询一条策略日志
   */
  private findSrategy () {
    const parentId = { parentId: this.divisionModel.id }
    this.dateStrategyService.findDateStrategyLog(parentId).subscribe(data => { this.dataHistory = data })
  }
  /**
   * 审批记录
   */
  private apply () {
    const caseTaskId = { caseTaskId: this.roleData.id, applyCategory: 'CASE_DATE_STRATEGY' }
    this.caseApplyRecordService.recordHistoryByTaskId(caseTaskId).subscribe(data => { this.dataset = data })
  }
  /**
   * 提交验证并并与数据库交互
   */
  private commit () {
    const Form: any = this.$refs["form"];
    Form.validate(valid => {
      if (!valid) return

      console.log('this.divisionModel', this.divisionModel.operationDate);

      const sort = (a, b) => a - b
      // if (this.divisionModel.operationDate) {
      // this.divisionModel.operationDate = this.divisionModel.operationDate.sort(sort).join(',')
      // }

      const result = this.divisionModel.id ? this.updateStrategy() : this.addStrategy();
    })
  }

  /**
   * 新增日期策略
   */
  private addStrategy (): boolean {
    console.log('divisionModel', this.divisionModel);

    // 暂不分案 将默认策略日期值为32传给后端
    this.dateStrategyService.saveDateStrategy({ ...this.divisionModel, operationDate: this.disableDate ? "32" : this.divisionModel.operationDate.join(',') }).subscribe(
      (data) => {
        this.$message.success('新增成功!');
        this.refreshList();
        this.close();
      }
    );
    return true;
  }

  private setDivisionState (state) {
    this.$nextTick(() => {
      this.divisionModel.divisionState = state
    })
  }


  private created () {
    console.log('this.roleData', this.roleData, this.type);
    // 默认是执行分案
    this.$nextTick(() => {
      if ((this.type !== 'OPERATION_ADD' && this.type !== 'OPERATION_SEE' )|| this.roleData.operationDate === '32') {
        this.disableData(this.roleData)
      }
      else {
        this.setDivisionState('do')
      }
    })
  }

  @Watch('divisionModel.divisionState', { immediate: true })
  private modelivisionStateChange () {
    this.divisionModel.divisionState === 'undo' ? this.disableDate = true : this.disableDate = false

  }

  private disableData (roleData) {
    console.log('roleData', roleData);
    if ((!roleData.editOperationDate || !roleData.editOperationDate.length) && roleData.operationDate === '32') {
      this.$nextTick(() => {
        this.divisionModel.divisionState = 'undo'
        this.disableDate = true
        this.rules.operationDate[0].required = false
      })
    } else {
      this.rules.operationDate[0].required = true
    }
  }

  @Watch('roleData')
  private roleDatChange (roleData) {
    this.disableData(roleData)
  }

  private divisionStateChange (val) {

    this.$nextTick(() => {
      this.divisionModel.operationDate = []
      if (val === 'undo') {
        this.disableDate = true
        this.rules.operationDate[0].required = false
        this.divisionModel.editOperationDate = []
      } else {
        this.disableDate = false
        this.rules.operationDate[0].required = true
      }
    })

  }

  /**
   * 修改日期策略
   */
  private updateStrategy (): boolean {
    this.dateStrategyService.updateStrategy({ ...this.divisionModel, operationDate: this.disableDate ? "32" : this.divisionModel.operationDate.join(',') }).subscribe(
      (data) => {
        this.$message.success('修改成功!');
        this.refreshList();
        this.close();
      }
    );
    return true;
  }
  /**
   * 修改日期策略之前数据处理
   */
  private beforeUpdating () {
    if (!this.divisionModel.operationDate.length) {
      return
    }

    const dateList = typeof this.divisionModel.operationDate === 'string' ?
      this.divisionModel.operationDate.split(',')
      : this.divisionModel.operationDate

    const arr = dateList.map(f => {
      return Number(f)
    }).filter(v => Number(v) !== 32)

    this.$nextTick(() => {
      if (!arr.length) {
        this.divisionModel.divisionState = 'undo'
        this.disableDate = true
      }
    })


    this.divisionModel.operationDate = arr
  }

  private mounted () {
    console.log('CommonState', this.$dict.getDictData('CommonState'))
  }
}
</script>

<style lang="less" scoped>
.paddingNone {
  padding: 0 !important;
}
.widthOne {
  width: 656px !important;
}
.widthTwo {
  width: 508px !important;
}
.widthThree {
  width: 620px !important;
}
.widthFour {
  width: 303px;
}
/deep/.el-select {
  line-height: 43px;
  margin-top: -5px;
  width: 93.3%;
  /deep/.el-input {
    width: 100% !important;
  }
}
#option {
  margin: 5px;
  width: 25px;
  height: 25px;
  line-height: 25px;
  padding-left: 9px;
  border: 1px solid #ebeef5;
}
/deep/#division .el-select__tags {
  -webkit-transform: translateY(-16%);
  transform: translateY(-16%);
  max-height: 75px !important;
  overflow-y: auto !important;
}
/deep/::-webkit-scrollbar {
  width: 7px;
}
/deep/::-webkit-scrollbar-track {
  background-color: #f5f5f5;
  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
}
/deep/::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}
/deep/::-webkit-scrollbar-button {
  background-color: #eee;
  display: none;
}
/deep/::-webkit-scrollbar-corner {
  background-color: black;
}
</style>
